package com.soledroid;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.*;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.*;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.*;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.github.droidfu.widgets.WebImageView;
import com.soledroid.Model.Comment;
import com.soledroid.Model.Dish;
import com.soledroid.Model.Stall;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;

public class DishActivity extends Activity{
	private LayoutInflater mInflater;

	static final int DIALOG_FORGOT_RATING_ID = 0;
	static final int DIALOG_FORGOT_COMMENT_ID = 1;

	protected int id;
	protected String name;

	private EditText dishCommentText;
	private RatingBar dishRatingBar;
	private ArrayList<Comment> comments;

	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dish);
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		
		mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

		id = getIntent().getExtras().getInt("id");
		name = getIntent().getExtras().getString("name");

		Dish dish = this.fetchDishInfo();

		TextView dishNameView = (TextView) findViewById(R.id.dish_name);
		RatingBar dishOverallRatingBar = (RatingBar) findViewById(R.id.dish_rating);
		TextView dishDescription = (TextView) findViewById(R.id.dish_desc);

		dishRatingBar = (RatingBar) findViewById(R.id.dishRating);
		dishCommentText = (EditText) findViewById(R.id.dishComment);
		imm.hideSoftInputFromWindow(dishCommentText.getWindowToken(), 0);
		Button submitBtn = (Button) findViewById(R.id.dishCommentSubmitBtn);
		ImageView dishImage = (ImageView) findViewById(R.id.dish_img);

		dishNameView.setText(name);
		if(dish.getDescription() == null || dish.getDescription().equals("") || dish.getDescription().equals("null")){
			dishDescription.setText("$" + dish.getPrice());
		} else{
			dishDescription.setText("$" + dish.getPrice() +  " - " + dish.getDescription());
		}
		
		dishOverallRatingBar.setRating((float)dish.getRating());

		try {
			dishImage.setImageDrawable(Drawable.createFromStream(Utils.fetchImage(dish.getImage()), "src"));
		} catch (Exception e) {
			e.printStackTrace();
		}

		comments = this.fetchComments();

		CustomAdapter adapter = new CustomAdapter(this, R.layout.comment_list_entry, R.id.comment_content, comments);
		ListView lv = (ListView) findViewById((R.id.commentListView));
		lv.setAdapter(adapter);

		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				Comment comment = comments.get(position);
				
				Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
				i.putExtra("id", comment.getUserId());
				
				DishActivity.this.startActivity(i);
			}
		});

		submitBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(dishCommentText.getText().toString().trim().equals("")){
					showDialog(DIALOG_FORGOT_COMMENT_ID);
					return;
				} 

				if(dishRatingBar.getRating() == 0){
					showDialog(DIALOG_FORGOT_RATING_ID);
					return;
				} 

				Toast.makeText(getApplicationContext(), "Submitting...", Toast.LENGTH_SHORT).show();

				addComment(dishCommentText.getText().toString(), (int)dishRatingBar.getRating());

			}
		});


	}

	public ArrayList<Comment> fetchComments()
	{
		ArrayList<Comment> listItems = new ArrayList<Comment>();

		try {
			URL url = new URL("http://soledroid.huytoan.com/dish/" + id + "/comments");
			URLConnection tc = url.openConnection();
			tc.setUseCaches(true);
			BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));

			String line;
			while ((line = in.readLine()) != null) {
				JSONArray ja = new JSONArray(line);

				for (int i = 0; i < ja.length(); i++) {
					JSONObject jo = (JSONObject) ja.get(i);
					Comment comment = new Comment(jo.getInt("id"), jo.getInt("type"), jo.getString("comment"), jo.getInt("rating"),
							jo.getInt("user_id"), jo.getInt("to_id"));
					listItems.add(comment);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		return listItems;
	}
	
	protected Dialog onCreateDialog(int id) {
		switch(id) {
		case DIALOG_FORGOT_RATING_ID:
			return new AlertDialog.Builder(DishActivity.this).setTitle("You forgot to rate this dish.").create(); 
		case DIALOG_FORGOT_COMMENT_ID:
			return new AlertDialog.Builder(DishActivity.this).setTitle("You forgot to write a review for this dish.").create();
		}

		return null;
	}

	public Dish fetchDishInfo()
	{
		Dish dish = null;

		try {
			URL url = new URL("http://soledroid.huytoan.com/dish/" + id);
			URLConnection tc = url.openConnection();
			tc.setUseCaches(true);
			BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));

			String line;
			while ((line = in.readLine()) != null) {
				JSONArray ja = new JSONArray(line);

				for (int i = 0; i < ja.length(); i++) {
					JSONObject jo = (JSONObject) ja.get(i);
					dish = new Dish(jo.getInt("id"), jo.getString("name"), jo.getString("image"),
							jo.getString("description"), jo.getString("price"), jo.getInt("stall_id"),
							jo.getInt("on_promotion") == 1, jo.getDouble("rating"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 

		return dish;
	}

	public void addComment(String comment, int rating) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost("http://soledroid.huytoan.com/comment");

		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("type", "2")); // 2 == dish
			nameValuePairs.add(new BasicNameValuePair("comment", comment));
			nameValuePairs.add(new BasicNameValuePair("rating", Integer.toString(rating)));
			nameValuePairs.add(new BasicNameValuePair("user_id", Integer.toString(getSharedPreferences("me", MODE_PRIVATE).getInt("id", 1))));
			nameValuePairs.add(new BasicNameValuePair("to_id", Integer.toString(id)));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			// Execute HTTP Post Request
			ResponseHandler<String> responseHandler=new BasicResponseHandler();
			String responseBody = httpclient.execute(httppost, responseHandler);
			JSONObject response = new JSONObject(responseBody);
			Toast.makeText(getApplicationContext(), response.getString("result"), Toast.LENGTH_LONG).show();
			
			dishCommentText.setText("");
			dishRatingBar.setRating(0);

			comments = this.fetchComments();

			CustomAdapter adapter = new CustomAdapter(this, R.layout.comment_list_entry, R.id.comment_content, comments);
			ListView lv = (ListView) findViewById((R.id.commentListView));
			lv.setAdapter(adapter);

		} catch(Exception e){
			e.printStackTrace();
		}
	}

	private class CustomAdapter extends ArrayAdapter<Comment> {
		public CustomAdapter(Context context, int resource, int textViewResourceId, List<Comment> objects) {
			super(context, resource, textViewResourceId, objects);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {   
			ViewHolder holder = null;
			RatingBar ratingBar = null;
			TextView commentView = null;
			WebImageView avatarView = null;
			Comment rowData = getItem(position);

			if(convertView == null) {
				convertView = mInflater.inflate(R.layout.comment_list_entry, null);
				holder = new ViewHolder(convertView);
				convertView.setTag(holder);
			}

			holder = (ViewHolder) convertView.getTag();

			ratingBar = holder.getRatingBar();
			ratingBar.setRating((float)(rowData.getRating()));

			commentView = holder.getCommentView();
			commentView.setText(rowData.getComment());


			avatarView = holder.getImageView();
			try {
				avatarView.setImageUrl("http://soledroid.huytoan.com/user/" + rowData.getUserId() + "/picture");
				avatarView.loadImage();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			return convertView;
		}
	}

	private class ViewHolder {
		private View mRow;
		private RatingBar mRatingBar = null;
		private TextView mCommentView = null;
		private WebImageView mImageView = null; 

		public ViewHolder(View row) {
			mRow = row;
		}

		public RatingBar getRatingBar() {
			if(mRatingBar == null) {
				mRatingBar = (RatingBar) mRow.findViewById(R.id.comment_rating);
			}

			return mRatingBar;
		}

		public TextView getCommentView() {
			if(mCommentView == null) {
				mCommentView = (TextView) mRow.findViewById(R.id.comment_content);
			}
			return mCommentView;
		}  

		public WebImageView getImageView() {
			if(mImageView == null){
				mImageView = (WebImageView) mRow.findViewById(R.id.comment_img);
			}
			return mImageView;
		}
	}
	 @Override
		public boolean onCreateOptionsMenu(Menu menu) {
			boolean result = super.onCreateOptionsMenu(menu);
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.menu, menu);
			return result;
		}
	    
	    @Override
		public boolean onOptionsItemSelected(MenuItem item) {
			Intent i;
			switch(item.getItemId()) {
			case R.id.menu_search:
				onSearchRequested();
				return true;
			case R.id.menu_preferences:
				showPreferences();
				return true;
			}
			return super.onOptionsItemSelected(item);
		}
	    
	    private void showPreferences() {
			Intent i = new Intent(this, SettingsActivity.class);
			startActivity(i);
		}

	
}
